package com.servlet;

import com.dao.imp.FindGoodsDaoImp;
import com.entity.Good;
import com.util.DBConn;
import net.sf.json.JSONArray;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Mathison
 * @Title: ${NAME}
 * @Package: ${PACKAGE_NAME}
 * @Description: TODO
 * @date 2021/11/23 17:28
 **/

@WebServlet(name = "GetGoodsListServlet", value = "/GetGoodsListServlet")
public class GetGoodsListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int choosePageNum = Integer.parseInt(request.getParameter("pageNum"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        int realStartIndex = (choosePageNum-1)*pageSize;
        response.setContentType("text/html;charset=utf-8");

        String selectSQL = "SELECT * FROM goods  ORDER BY `good_id` LIMIT "+realStartIndex+","+pageSize;

//        System.out.println("selectSQL"+selectSQL);

        FindGoodsDaoImp findGoodsDaoImp = new FindGoodsDaoImp();
        List<Map> goods = findGoodsDaoImp.findGoods(selectSQL);
        List<Good> goodList = new ArrayList<>();
        for (int i = 0; i < goods.size(); i++) {
            Good good = new Good();

            good.setGood_id(Integer.valueOf(goods.get(i).get("good_id").toString()));
            good.setGood_url(goods.get(i).get("imgUrls").toString());
            good.setSubtitle(goods.get(i).get("subtitle").toString());
            good.setGood_parentType(goods.get(i).get("good_parentType").toString());
            good.setGood_childType(goods.get(i).get("good_childType").toString());
            good.setGood_name(goods.get(i).get("good_name").toString());
            good.setGood_price(Double.valueOf(goods.get(i).get("good_price").toString()));
            good.setGood_sales(Integer.valueOf(goods.get(i).get("good_sales").toString()));
            good.setMerchant_id(Integer.valueOf(goods.get(i).get("merchant_id").toString()));
            good.setGood_information(goods.get(i).get("good_information").toString());
            good.setGood_remainingAmount(Integer.valueOf(goods.get(i).get("good_remainingAmont").toString()));
            good.setStatus(Integer.valueOf(goods.get(i).get("status").toString()));

            goodList.add(good);
        }

        JSONArray json = JSONArray.fromObject(goodList);
//        System.out.println(json);
        response.getWriter().print(json);
    }
}
